const sequelize = require('../config/database');
const fs = require('fs').promises;
const path = require('path');

async function cleanupIndexes() {
  try {
    console.log('开始清理重复索引...');

    // 读取 SQL 文件
    const sqlPath = path.join(__dirname, '../config/cleanup-indexes.sql');
    const sqlContent = await fs.readFile(sqlPath, 'utf8');

    // 分割 SQL 语句
    const statements = sqlContent
      .split(';')
      .map(statement => statement.trim())
      .filter(statement => statement.length > 0);

    // 执行每个 SQL 语句
    for (const statement of statements) {
      try {
        await sequelize.query(statement + ';');
      } catch (error) {
        // 如果是因为索引不存在而失败，我们可以忽略这个错误
        if (!error.message.includes('FOREIGN KEY') && !error.message.includes('INDEX')) {
          throw error;
        }
      }
    }

    console.log('索引清理完成！');
    process.exit(0);
  } catch (error) {
    console.error('清理索引失败:', error);
    process.exit(1);
  }
}

cleanupIndexes(); 